package com.xindaoapp.henghua.activity;

import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.pm.PackageManager.NameNotFoundException;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.WindowManager;

import com.loopj.android.http.util.EnergyError;
import com.loopj.android.http.util.Response.ErrorListener;
import com.loopj.android.http.util.Response.Listener;
import com.xindaoapp.henghua.R;
import com.xindaoapp.henghua.application.XinDaoApplication;
import com.xindaoapp.henghua.entry.UserInfo;
import com.xindaoapp.henghua.utils.MoccaPreferences;

/**
 * 启动页面，判断是否自动登录或者跳转登录
 * @author chenghao
 *
 */
public class SplashActivity extends Activity {
	protected static final int DIALOG_LOADING = 1;// 数据加载
	protected static final int DIALOG_LOGIN = 2;// 登录
	protected static final int DIALOG_SUBMIT = 3;// 提交

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		getWindow().setSoftInputMode(
				WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE
						| WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
		super.onCreate(savedInstanceState);
		setContentView(R.layout.layout_main);
		String deviceId = MoccaPreferences.DeviceId.get();
		if (TextUtils.isEmpty(deviceId)) {
			Intent intent = new Intent(this, EnterDevicd.class);
			startActivity(intent);
			finish();
		} else {
			XinDaoApplication
					.get()
					.getMoccaApi()
					.login(getPackageName(), getVersionName(), EnterDevicd.GIIPVERSION, deviceId,
							new Listener<UserInfo>() {

								@Override
								public void onResponse(UserInfo response) {
									// 跳转主页
									if (null != response) {
										XinDaoApplication.get().setUserInfo(response);
										Intent intent = new Intent(getBaseContext(),
												DeviceEngineerActivity.class);
										startActivity(intent);
										finish();
									} else {
										removeDialog(DIALOG_LOGIN);
									}
								}
							}, new ErrorListener() {

								@Override
								public void onErrorResponse(EnergyError error) {
									removeDialog(DIALOG_LOGIN);
								}
							});
		}
	}

	private String getVersionName() {
		try {
			return getPackageManager().getPackageInfo(getPackageName(), 0).versionName;
		} catch (NameNotFoundException e) {
			e.printStackTrace();
		}
		return "";
	}

	@Override
	@Deprecated
	protected Dialog onCreateDialog(int id) {
		ProgressDialog pd = new ProgressDialog(this);
		switch (id) {
		case DIALOG_LOADING:
			pd.setTitle(R.string.msg_hint);
			pd.setMessage(getString(R.string.loading_data));
			pd.setCancelable(false);
			return pd;
		case DIALOG_LOGIN:
			pd.setTitle(R.string.msg_hint);
			pd.setMessage(getString(R.string.loading_login));
			pd.setCancelable(false);
			return pd;
		case DIALOG_SUBMIT:
			pd.setTitle(R.string.msg_hint);
			pd.setMessage(getString(R.string.loading_data));
			pd.setCancelable(false);
			return pd;
		}
		return null;
	}
}
